package com.zhengxiang.onlinexamination.service.impl;

import com.zhengxiang.onlinexamination.base.CacheConstants;
import com.zhengxiang.onlinexamination.base.Constants;
import com.zhengxiang.onlinexamination.base.UserConstants;
import com.zhengxiang.onlinexamination.component.AsyncFactory;
import com.zhengxiang.onlinexamination.component.AsyncManager;
import com.zhengxiang.onlinexamination.component.AuthenticationContextHolder;
import com.zhengxiang.onlinexamination.component.exception.user.UserErrorCode;
import com.zhengxiang.onlinexamination.component.exception.user.UserException;
import com.zhengxiang.onlinexamination.entity.SysUser;
import com.zhengxiang.onlinexamination.service.SysPasswordService;
import com.zhengxiang.onlinexamination.utils.MessageUtils;
import com.zhengxiang.onlinexamination.utils.RedisCache;
import com.zhengxiang.onlinexamination.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class SysPasswordServiceImpl implements SysPasswordService {

    @Autowired
    private RedisCache redisCache;

    @Value(value = "${user.password.maxRetryCount}")
    private int maxRetryCount;

    @Value(value = "${user.password.lockTime}")
    private int lockTime;

    /**
     * 登录账户密码错误次数缓存键名
     *
     * @param username 用户名
     * @return 缓存键key
     */
    @Override
    public String getCacheKey(String username) {
        return CacheConstants.PWD_ERR_CNT_KEY + username;
    }

    @Override
    public void validate(SysUser user) {
        Authentication usernamePasswordAuthenticationToken = AuthenticationContextHolder.getContext();
        String username = usernamePasswordAuthenticationToken.getName();
        String password = usernamePasswordAuthenticationToken.getCredentials().toString();

        Integer retryCount = redisCache.getCacheObject(getCacheKey(username));

        if (retryCount == null) {
            retryCount = 0;
        }

        if (retryCount >= Integer.valueOf(maxRetryCount).intValue()) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL,
                    MessageUtils.message("user.password.retry.limit.exceed", maxRetryCount, lockTime)));
            throw new UserException(UserErrorCode.LOGIN_FAIL_ERROR,MessageUtils.message("user.password.retry.limit.exceed", maxRetryCount, lockTime));
        }

        if (!matches(user, password)) {
            retryCount = retryCount + 1;
            AsyncManager me = AsyncManager.me();
            me.execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL,
                    MessageUtils.message("user.password.retry.limit.count", retryCount)));
            redisCache.setCacheObject(getCacheKey(username), retryCount, lockTime, TimeUnit.MINUTES);
            throw new UserException(UserErrorCode.LOGIN_FAIL_ERROR,MessageUtils.message("user.password.retry.limit.exceed", maxRetryCount, lockTime));
        } else {
            clearLoginRecordCache(username);
        }
    }
    @Override
    public boolean matches(SysUser user, String rawPassword) {
        return SecurityUtils.matchesPassword(rawPassword, user.getUserPassword());
    }
    @Override
    public void clearLoginRecordCache(String loginName) {
        if (redisCache.hasKey(getCacheKey(loginName))) {
            redisCache.deleteObject(getCacheKey(loginName));
        }
    }
}
